

let socket;
import { Message } from 'element-ui'
//引入仓库
import store from "@/store";
const state = {

    messages: [],
    chatUser : {},
    chatGroupRoom:{},
    croupUsers:[],
    users : [],
    content: '',
    noRead: false,
    webOpen: false


};
const actions = {
    //发送信息
    async WebSocketSend({dispatch, state, commit}, sendInfo) {
        // 组装待发送的消息 json
        // {"from": "zhang", "toUserName": "admin", "messageText": "聊天文本"}
        console.log('发送')
        console.log(sendInfo.messageText)
        let user = sendInfo.user
        let message = {fromId: user.id, toUserId: sendInfo.chatUser.id, messageText: sendInfo.messageText,num: sendInfo.chatUser.num}
        if (socket != null){
            socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
            state.messages.push(message)
            // 构建消息内容，本人消息
            dispatch('MessageContent', {
                remoteUser: null,
                nowUser: user,
                messageText: sendInfo.messageText,
                toUserId: sendInfo.chatUser.id
            })
        }else {
            Message({message: '与服务断开了连接', type: 'error', showClose: true});
        }
    },
     WebSocketComm({dispatch,state,commit}) {
        // 从user仓库中获取登录用户数据
        let user = store.state.user.userInfo
        //判断浏览器是否支持WebSocket
        if (typeof (WebSocket) == "undefined") {
            Message({message: '当前浏览器不支持WebSocket', type: 'error', showClose: true});
        } else {
            console.log("您的浏览器支持WebSocket");
            let userId = user.id
            let socketUrl = "ws://localhost:9000/comm/chat/" + userId;
            if (socket != null) {
                socket.close();
                socket = null;
            }
            // 开启一个websocket服务
             socket = new WebSocket(socketUrl);
            //打开事件
             socket.onopen = function () {
                console.log("websocket已打开");
                state.webOpen = true
                 dispatch('OrderMumCount')
            };
            //  浏览器端收消息，获得从服务端发送过来的文本消息
            socket.onmessage = function (msg) {
                console.log("收到数据====" + msg.data)
                 let resultData = JSON.parse(msg.data)
                //用户登录消息
                if (resultData.loginTo) {
                    state.users.forEach((item)=>{
                        if (item.userId == resultData.loginTo.userId){
                            item.userInfo.loginState = true;
                        }
                    })
                }
                //用户退出登录消息
                if (resultData.logOut) {
                    state.users.forEach((item)=>{
                        if (item.userId == resultData.logOut.userId){
                            item.userInfo.loginState = false;
                        }
                    })
                }
                //新增联系人消息
                if (resultData.addUser) {
                        state.users.push(resultData.addUser)
                }
                // 通知发起订单用户消息
                if (resultData.commGroupUser) {
                    dispatch('ReceiveTip',resultData.commGroupUser)
                }
                // 通知订单帮助用户消息
                if (resultData.commGroupHelpUser) {
                    dispatch('HelpReceiveTip',resultData.commGroupHelpUser)
                }
                if(resultData.croupUsers) {
                    console.log("前端收到数据11111111");
                    console.log(resultData.croupUsers);
                    commit("CroupUsers",resultData.croupUsers)
                }
                //获取用户列表消息
                if (resultData.users) {
                    //如果是[user{},user{}]
                    // 获取非自己的在线人员
                    //对在线列表进行过滤
                    let users = resultData.users.filter(user => user.userId !== userId)
                    commit("WebSocketUser",users)
                }
                //接收聊天消息
                if (resultData.fromUser) {
                    //当前url
                    let url = window.location.href
                        if (url.substring(url.length- 5) !== '/chat'){
                            state.noRead = true;
                        }
                        state.messages.push(resultData)
                        // 构建消息内容
                        dispatch('MessageContent',{remoteUser:resultData.fromUser, nowUser:null, messageText:resultData.message})
                }
            };
            //关闭事件
            socket.onclose = function () {
                state.webOpen = false
                dispatch('Logout')
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function () {
                state.webOpen =false
                dispatch('Logout')
                console.log("websocket发生了错误");
            }
        }
    },
    //聊天内容创建model
    MessageContent({state,commit},viewInfo) {
        console.log(viewInfo+'viewInfo')// 这个方法是用来将 json的聊天消息数据转换成 html的。
        let html
        // 当前用户消息
        if (viewInfo.nowUser) { // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
            html = "<div class=\"el-row\" style=\"padding: 5px 0;margin-top: 7px\">\n" +
                "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px\">\n" +
                "    <div class=\"tip left\">" + viewInfo.messageText + "</div>\n" +
                "  </div>\n" +
                "  <div class=\"el-col el-col-2\">\n" +
                "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
                "    <img src=\""+ viewInfo.nowUser.photoUrl +"\" style=\"object-fit: cover;\">\n" +
                "  </span>\n" +
                "  </div>\n" +
                "</div>";
            state.content += html
            var chatData = sessionStorage.getItem(viewInfo.toUserId)
            if (chatData != null){
                chatData +=html
            }
            sessionStorage.setItem(viewInfo.toUserId,chatData)
        } else if (viewInfo.remoteUser) {   // remoteUser表示远程用户聊天消息，蓝色的气泡
            html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
                "  <div class=\"el-col el-col-2\" style=\"text-align: right\">\n" +
                "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
                "    <img src=\""+ viewInfo.remoteUser.photoUrl +"\" style=\"object-fit: cover;\">\n" +
                "  </span>\n" +
                "  </div>\n" +
                "  <div class=\"el-col el-col-22\" style=\"text-align: left; padding-left: 10px\">\n" +
                "    <div class=\"tip right\">" + viewInfo.messageText + "</div>\n" +
                "  </div>\n" +
                "</div>";
            if (state.chatUser.id == viewInfo.remoteUser.id){
                state.content += html
                sessionStorage.setItem(state.chatUser.id,state.content)
            }else {
                state.users.forEach((item)=>{
                    if (item.userId == viewInfo.remoteUser.id) {
                        item.userInfo.noReadNum++
                    }
                })
                var chatData1 = sessionStorage.getItem(viewInfo.remoteUser.id)
                if (chatData1 != null){
                    chatData1 += html
                    sessionStorage.setItem(viewInfo.remoteUser.id,chatData1)
                }else {
                    sessionStorage.setItem(viewInfo.remoteUser.id,html)
                }
            }

        }
    },
    //关闭连接
    DownWebSocket(){
        if (socket != null) {
            socket.close();
            socket = null;
        }
    },
    // 更新对话用户
    UpdateChatUser({dispatch,state,commit},chatUser){
        commit("UpdateChatUser",chatUser)
        if (chatUser.noReadNum !=0)
        state.users.forEach((item)=>{
            if (item.userId == chatUser.id) {
                item.userInfo.noReadNum = 0
            }
        })

        var chatData =  sessionStorage.getItem(chatUser.id);
        if (chatData !=null) {
            //将聊天记录渲染到聊天区
            state.content = chatData
        }else {
            sessionStorage.setItem(chatUser.id,'')
            state.content = ''
        }
    },
    //更新未读状态
    UpdateRead({state}){
        state.noRead = false
    }

};
const mutations = {
    // 群聊列表
    CroupUsers(state,croupUsers){
        state.croupUsers = croupUsers;
    },
    //联系人列表
    WebSocketUser(state,users){
        state.users = users
        // users.forEach((items)=>{
        //     state.users.forEach((items1)=>{
        //         if(items.userId===items1.userId){
        //             items1.userInfo.loginState=true;
        //             items.userId = '';
        //     }
        //     })
        //     if (items.userId !== ''){
        //         state.users.push(items)
        //     }
        // })
    },
    UpdateChatUser(state,chatUser){
        state.chatUser = chatUser
    }

};
const getters = {};
export default {
    state,
    mutations,
    actions,
    getters,
}
